<template>
<div></div>
</template>

<script>
import * as esriLoader from "esri-loader";
import MapManager from "../../../core/mapManager";
export default {
    name: "iQuery",
    components: {},
    props: {},
    data() {
        return {
            mapView: null,
            iQueryActiveState: false, //当前查询状态，true为可以查询，false为不可以查询
            popupSelectedFeature: null,
            hiddenFields: window.g.MapConfiguration.HiddenFields,
            PopupShowAttr: window.g.MapConfiguration.PopupShowAttr,
        }
    },
    methods: {
        initIquery() {
            const self = this;
            self.iQueryActiveState = true;
            self.mapView = MapManager.getMapViewByID("mainMap");
            self.mapView.cursor = "help";
            let cursorOld = "help"; 
            esriLoader
                .loadModules([
                    "esri/Map",
                    "esri/views/MapView",
                    "esri/views/SceneView",
                    "esri/geometry/Point",
                    'esri/geometry/Polyline',
                    "esri/geometry/Polygon",
                    "esri/geometry/Extent",
                    "esri/layers/TileLayer",
                    "esri/layers/support/TileInfo",
                    "esri/layers/MapImageLayer",
                    "esri/layers/FeatureLayer",
                    "esri/layers/WebTileLayer",
                    "esri/layers/WMTSLayer",
                    "esri/geometry/SpatialReference",
                    "esri/Basemap",
                    "esri/widgets/BasemapToggle",
                    "esri/core/watchUtils",
                    "esri/widgets/ScaleBar",
                    "esri/tasks/IdentifyTask",
                    "esri/tasks/support/IdentifyParameters",
                    "esri/Graphic",
                    "esri/widgets/Compass",
                    "esri/tasks/GeometryService",
                    "esri/layers/GraphicsLayer",
                    'esri/geometry/geometryEngine',
                    'esri/tasks/support/BufferParameters',
                    "esri/widgets/Slice",
                    'esri/config',
                ])
                .then(
                    ([
                        Map,
                        MapView,
                        SceneView,
                        Point,
                        Polyline,
                        Polygon,
                        Extent,
                        TileLayer,
                        TileInfo,
                        MapImageLayer,
                        FeatureLayer,
                        WebTileLayer,
                        WMTSLayer,
                        SpatialReference,
                        Basemap,
                        BasemapToggle,
                        watchUtils,
                        ScaleBar,
                        IdentifyTask,
                        IdentifyParameters,
                        Graphic,
                        Compass,
                        GeometryService,
                        GraphicsLayer,
                        geometryEngine,
                        BufferParameters,
                        Slice,
                        esriConfig
                    ]) => {
                        self.Point = Point;
                        self.Polyline = Polyline;
                        self.Extent = Extent;
                        self.FeatureLayer = FeatureLayer;
                        self.Polygon = Polygon;
                        self.Graphic = Graphic;
                        self.GeometryService = GeometryService;
                        self.GraphicsLayer = GraphicsLayer
                        self.geometryEngine = geometryEngine
                        self.BufferParameters = BufferParameters
                        self.Slice = Slice
                        // 识别流程
                        self.clickHandler = self.mapView.on("click", (e) => {
                            if (!self.iQueryActiveState) {
                                //属性查询功能开启时不进入事件操作
                                return;
                            }
                            if (self.popupSelectedFeature) {
                                self.mapView.graphics.remove(self.popupSelectedFeature);
                                self.popupSelectedFeature = null;
                            }
                            let goIdentify = true;
                            self.mapView.hitTest(e.screenPoint).then((hitResponse) => {
                                if (hitResponse.results.length) {
                                    const getGraphic = hitResponse.results.find((hitResult) => {
                                        return (hitResult.graphic.popupTemplate || (hitResult.graphic.layer && hitResult.graphic.layer.popupTemplate) || (hitResult.graphic.layer && hitResult.graphic.layer.customPopupID));
                                    });
                                    if (getGraphic) {
                                        goIdentify = false;
                                    }
                                }
                                // 进入识别查询
                                if (goIdentify && self.mapView.map && self.mapView.map.allLayers) {
                                    self.mapView.cursor = "wait";
                                    let promise = [];
                                    self.mapView.map.allLayers.items.forEach((l, i) => {
                                        if (l.type == "vector-tile") {
                                            self.$message.info("当前图层不支持i查询")
                                        } else {
                                            // if (!l.isBaseMap && l.url && ["feature", "graphics", "map-image", "tile" ,"vector-tile"].indexOf(l.type) != -1) {
                                            if (!l.isBaseMap && l.url && ["feature", "graphics", "map-image", "tile"].indexOf(l.type) != -1) {
                                                const p = new Promise((identifyResolve, reject) => {
                                                    let identifyTask = new IdentifyTask(l.url);
                                                    // if(l.type == "vector-tile"){
                                                    //     identifyTask = new IdentifyTask(l.queryurl);
                                                    // }
                                                    const params = new IdentifyParameters();
                                                    params.tolerance = 8;
                                                    params.geometry = e.mapPoint;
                                                    params.width = self.mapView.width;
                                                    params.height = self.mapView.height;
                                                    params.returnGeometry = true;
                                                    params.layerOption = "visible";
                                                    params.mapExtent = self.mapView.extent;
                                                    identifyTask
                                                        .execute(params)
                                                        .then((identifyResponse) => {
                                                            if (identifyResponse && identifyResponse.results && identifyResponse.results.length > 0) {
                                                                const resFeatures = [];
                                                                identifyResponse.results.forEach((iFeature) => {
                                                                    iFeature.layerTitle = l.title;
                                                                    resFeatures.push(iFeature);
                                                                });
                                                                identifyResolve({
                                                                    type: true,
                                                                    features: resFeatures,
                                                                });
                                                            } else {
                                                                identifyResolve({
                                                                    type: false
                                                                });
                                                            }
                                                        })
                                                        .catch((identifyError) => {
                                                            console.error("识别出错：", identifyError);
                                                            identifyResolve({
                                                                type: false
                                                            });
                                                        });
                                                });
                                                promise.push(p);
                                            }
                                        }
                                    });
                                    if (promise.length > 0) {
                                        Promise.all(promise)
                                            .then((identifyResults) => {
                                                let identifyFeatures = [];
                                                identifyResults.forEach((r) => {
                                                    if (r.type) {
                                                        r.features.forEach((f) => {
                                                            const popupContentFields = [];
                                                            for (let field in f.feature.attributes) {
                                                                if (self.hiddenFields.indexOf(field.toUpperCase()) === -1) {
                                                                    if (f.feature.attributes[field] === null || f.feature.attributes[field] === "Null") {
                                                                        f.feature.attributes[field] = "";
                                                                    }
                                                                    popupContentFields.push({
                                                                        fieldName: field,
                                                                        label: self.PopupShowAttr[field] == undefined ? field : self.PopupShowAttr[field],
                                                                    });
                                                                }
                                                            }
                                                            const g = new Graphic({
                                                                geometry: f.feature.geometry,
                                                                attributes: f.feature.attributes,
                                                                symbol: window.g.MapConfiguration.HighlightSymbol[f.feature.geometry.type],
                                                                popupTemplate: {
                                                                    title: "<div style='background:transparent;'>" + f.layerTitle + "</div>",
                                                                    // fieldInfos: popupContentFields,
                                                                    // actions: [{
                                                                    //   id: "details",
                                                                    //   className: 'esri-icon-drag-horizontal',
                                                                    //   title: "详细信息",
                                                                    //   attributes: f.feature.attributes,
                                                                    //   geometry: f.feature.geometry,
                                                                    // }],
                                                                    content: [{
                                                                        type: "fields",
                                                                        fieldInfos: popupContentFields,
                                                                    }, ],
                                                                },
                                                            });
                                                            identifyFeatures.push(g);
                                                        });
                                                    }
                                                });
                                                if (identifyFeatures.length > 0) {
                                                    self.mapView.popup.open({
                                                        features: identifyFeatures,
                                                        featureMenuOpen: true,
                                                        // fetchFeatures: true,
                                                        updateLocationEnabled: true,
                                                    });
                                                    setTimeout(() => {
                                                        try {
                                                            var list = document.getElementById("tempClosePopBtn");
                                                            list.removeChild(list.childNodes[0]);
                                                        } catch (error) {}
                                                        $(".esri-popup__feature-menu-header").append(
                                                            " <span id='tempClosePopBtn' style='float:right;cursor: default;' class='esri-popup__icon1 esri-icon-close'></span>"
                                                        );
                                                        setTimeout(() => {
                                                            $("#tempClosePopBtn").on("click", function () {
                                                                if (self.popupSelectedFeature) {
                                                                    self.mapView.graphics.remove(
                                                                        self.popupSelectedFeature
                                                                    );
                                                                    self.popupSelectedFeature = null;
                                                                }
                                                                self.mapView.popup.visible = false;
                                                            });
                                                        }, 10);
                                                    }, 100);
                                                }
                                                setTimeout(() => {
                                                    self.mapView.cursor = cursorOld;
                                                }, 100);
                                            })
                                            .catch((identifyResultsError) => {
                                                self.mapView.cursor = cursorOld;
                                                console.error(identifyResultsError);
                                            });
                                    } else {
                                        self.mapView.cursor = cursorOld;
                                    }
                                } else {
                                    self.mapView.cursor = cursorOld;
                                }
                            });
                        });
                        self.popupVisibleWatcher = watchUtils.watch(
                            self.mapView.popup,
                            "visible",
                            (e) => {
                                if (!self.iQueryActiveState) {
                                    //属性查询功能开启时不进入事件操作
                                    return;
                                }
                                if (e === false) {
                                    if (self.popupSelectedFeature) {
                                        self.mapView.graphics.remove(self.popupSelectedFeature);
                                        self.popupSelectedFeature = null;
                                    }
                                }
                            }
                        );
                        self.popupSelectedFeautureWatcher = watchUtils.watch(
                            self.mapView.popup,
                            "selectedFeature",
                            (sFeature) => {
                                if (!self.iQueryActiveState) {
                                    //属性查询功能开启时不进入事件操作
                                    return;
                                }
                                if ( sFeature && (!sFeature.class || (sFeature.class && sFeature.class.indexOf("customCluster") === -1)) &&  (!sFeature.layer || (sFeature.layer && ["feature", "building-scene", "scene"].indexOf( sFeature.layer.type ) === -1))  ) {
                                    if (self.popupSelectedFeature) {
                                        self.mapView.graphics.remove(self.popupSelectedFeature);
                                        self.popupSelectedFeature = null;
                                    }
                                    self.popupSelectedFeature = new Graphic({
                                        geometry: sFeature.geometry,
                                        attributes: sFeature.attributes,
                                        symbol: window.g.MapConfiguration.HighlightSymbol[
                                            sFeature.geometry.type
                                        ],
                                    });
                                    self.mapView.graphics.add(self.popupSelectedFeature);
                                }
                            }
                        );

                    }
                )
                .catch((e) => {
                    console.error("初始化地图出错——");
                    console.error(e);
                });
        },
        closeIquery() {
            $("#tempClosePopBtn").click();
            this.mapView.cursor = "default";
            if (this.clickHandler) {
                this.clickHandler.remove();
                this.clickHandler = undefined;
            }
            if (this.popupVisibleWatcher) {
                this.popupVisibleWatcher.remove();
                this.popupVisibleWatcher = undefined;
            }
            if (this.popupSelectedFeautureWatcher) {
                this.popupSelectedFeautureWatcher.remove();
                this.popupSelectedFeautureWatcher = undefined;
            }
            if (this.popupSelectedFeature) {
                this.mapView.graphics.remove(this.popupSelectedFeature);
                this.popupSelectedFeature = null;
            }
        }
    },
    beforeDestroy() {
        this.closeIquery();
    }
}
</script>

<style>
</style>
